//
//  ScoreTeacherViewController.m
//  iBaby365v2
//
//  Created by Kirinrin on 14-7-14.
//  Copyright (c) 2014年 suplus. All rights reserved.
//

#import "ScoreTeacherViewController.h"
#import "ScoreTeacherShortCutViewController.h"
#import "ScoreTeacherStandardViewController.h"
#import "NetworkAccessManager.h"
#import "ChildInfo.h"
#import "UIAlertView+Kirinrin.h"

@interface ScoreTeacherViewController ()<UIAlertViewDelegate>

@property (nonatomic,weak)UIButton *selectbutton;
@property (nonatomic,assign)int index;
@end

@implementation ScoreTeacherViewController{
    ScoreTeacherShortCutViewController *_scoreTeacherShortCutViewController;
    ScoreTeacherStandardViewController *_scoreTeacherStandardViewController;
    
    UIActivityIndicatorView *activityIndicator;
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (id)initWithCoder:(NSCoder *)aDecoder{
    NSLog(@"initWithCoder");
    self = [super initWithCoder:aDecoder];
    if (self) {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
        
         _scoreTeacherShortCutViewController = [storyboard instantiateViewControllerWithIdentifier:@"ScoreTeacherShortCutView"];
        _scoreTeacherShortCutViewController.cParentViewController = self;
        //        parentListViewController.title = @"动态";
        
        _scoreTeacherStandardViewController = [storyboard instantiateViewControllerWithIdentifier:@"ScoreTeacherAddView"];
        _scoreTeacherStandardViewController.cParentViewController = self;
        //        chatHistoryViewController.title = @"家长列表";
        
        self.viewControllers = @[_scoreTeacherShortCutViewController, _scoreTeacherStandardViewController];
//        self.selectedIndex = 1;
        
        activityIndicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        activityIndicator.color = [UIColor blackColor];
        
        [self queryClassChild];
        
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    _allChildArray = [[NSMutableArray alloc]init];
    _selectedChildArray  = [[NSMutableArray alloc]init];
    _unSelectedChildArray  = [[NSMutableArray alloc]init];
}

-(void)setSelectedIndex:(NSUInteger)index animated:(BOOL)animated
{
    if (_index != index && self.selectedViewController.tabBarItem.title != NULL) {
        _index = index;
        NSMutableString *message = [NSMutableString stringWithString:@"是否确认离开"];
        [message appendString:self.selectedViewController.tabBarItem.title];
        [message appendString:@"模式,选择确认 之前的信息将被清除！"];
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
        alert.tag = 10;
        [alert show];
        
    }else{
        [super setSelectedIndex:index animated:NO];
    }
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - remote access action
-(void)queryClassChild{
    //FIX: 当load不到时，后续的操作可能出错
    
    AppDelegate *delegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    
    NSString *uriString = [NSString stringWithFormat:@"Child/%@/queryClassChild.json", delegate.user[@"kClassId"]];
    
    NSDictionary *parameters = @{@"key": delegate.accessKey};
    
    [[NetworkAccessManager shareManager]GET:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
        
        int resultCode = [responseObject[@"result"]intValue];
        if (resultCode == 0) {
            [self.allChildArray removeAllObjects];
            
            for (NSDictionary *data in responseObject[@"data"]) {
                [self.allChildArray addObject:[[ChildInfo alloc]initWithDictionary:data]];
            }
            self.unSelectedChildArray = [[NSMutableArray alloc]initWithArray:self.allChildArray];
            
            _scoreTeacherShortCutViewController.allChildArray = self.allChildArray;
            _scoreTeacherShortCutViewController.selectedChildArray = self.selectedChildArray;
            _scoreTeacherShortCutViewController.unSelectedChildArray = self.unSelectedChildArray;
            
            _scoreTeacherStandardViewController.allChildArray = self.allChildArray;
            
            
        }else{
            [UIAlertView alertWithRemoteError:resultCode];
        }
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"opernation: %@\nerror: %@", operation, error);
        [UIAlertView alertWithNetworkError];
    }];
}


- (IBAction)sendAction:(id)sender {

    //confirm
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"确认发送孩子评分吗？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];

    [alert show];
    
    //hide waiter
}



-(void)sendDataToRemote{
    
    
    if (self.selectedIndex == 0) {
        // shortCut select
        //        scoreData = [_scoreTeacherShortCutViewController getChildScore];
        [_scoreTeacherShortCutViewController.view endEditing:YES];
        int option0 = _scoreTeacherShortCutViewController.option0;
        int option1 = _scoreTeacherShortCutViewController.option1;
        int option2 = _scoreTeacherShortCutViewController.option2;
        int option3 = _scoreTeacherShortCutViewController.option3;
        for (ChildInfo *child in self.unSelectedChildArray) {
            [child setScoreOption:option0 :option1 :option2 :option3];
        }
    }else{
        //standard select
        [_scoreTeacherStandardViewController.view endEditing:YES];
    }
    
    
    
    //show waiter
    self.view.userInteractionEnabled = NO;
    activityIndicator.center = self.view.center;
    [activityIndicator startAnimating];
    [self.view addSubview:activityIndicator];
    
    //send data
    
    NSArray *scoreData = [ChildInfo getScoreDataFromChildArray:self.allChildArray];
    NSError *error ;
    NSData *jsonData = [NSJSONSerialization dataWithJSONObject:scoreData options:NSJSONWritingPrettyPrinted error:&error];
    if (error) {
        NSLog(@"error occour %@", error);
        return;
    }
    
    NSString *jsonString = [[NSString alloc] initWithData:jsonData encoding:NSUTF8StringEncoding];
    NSLog(@"json string %@", jsonString);
    
    
    NSString *uriString = @"Score.json";
    NSDictionary *parameters = @{@"key": self.appDelegate.accessKey, @"addition":jsonString};
    //    [parameters setObject:scoreData forKey:@"addition"];
    //    [parameters setObject:@"customeId" forKey:@"childId"];
    //    [parameters setObject:@"afafadfasfasf" forKey:@"addition"];
    
    [[NetworkAccessManager shareManager]POST:uriString parameters:parameters success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSLog(@"opernation: %@\nresponse: %@", operation, responseObject);
        
        
        int resultCode = [responseObject[@"result"]intValue];
        if (resultCode == 0) {
            [UIAlertView alertWithTitle:@"消息" message:@"评分发送成功！"];
        }else{
            [UIAlertView alertWithRemoteError:resultCode];
        }
        self.view.userInteractionEnabled = YES;
        [activityIndicator removeFromSuperview];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"opernation: %@\nerror: %@", operation, error);
        self.view.userInteractionEnabled = YES;
        [activityIndicator removeFromSuperview];
        [UIAlertView alertWithNetworkError];
    }];
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(alertView.tag == 10){
        switch (buttonIndex) {
            case 0:{
                _index = self.selectedIndex;
                [self setSelectedIndex:_index animated:NO];
                break;
            }
            case 1:{
                [self setSelectedIndex:_index animated:NO];
                break;
            }
            default:
                break;
        }
    }else{
        switch (buttonIndex) {
            case 0:
            
                break;
            case 1:
                [self sendDataToRemote];
                break;
        }
    }
}
@end
